package com.jch.sc.codec;

import com.jch.sc.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ObjDecoder extends ByteToMessageDecoder {

    private Class<?> genericType;

    public ObjDecoder(Class<?> genericType) {
        this.genericType = genericType;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int length = in.readInt();
        if (in.readableBytes() < length){
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[length];
        in.readBytes(data);
        out.add(SerializationUtil.deserialize(data,genericType));
    }
}
